<?php

namespace app\api\controller;

use app\api\controller\Common;
use app\api\validate\UniversalValidate;
use think\Controller;
use think\facade\Cache;
use think\facade\Hook;
use think\helper\Time;
use think\Request;
use ztouch\ZeroTouch;
use think\Db;

class Base extends Controller
{
    /**
     * 公共touch类
     */
    protected $zero_touch;

    /**
     * 公共Common
     */
    protected $common;

    /**
     * con_validate
     */
    protected $con_validate;

    /**
     * timer
     */
    protected $timer;

    // 初始化方法
    public function initialize()
    {
        parent::initialize();
        \think\facade\Hook::listen('response_send'); // 跨域
        $this->zero_touch   = new ZeroTouch();
        $this->common       = new Common();
        $this->con_validate = new UniversalValidate();
        $this->timer        = new Time();
        // 验证token和终端设备
        $token         = request()->header('token');
        $remote_device = request()->header('remote-device');
        if (!$token || !$remote_device) {$this->redirect(url('login/notLogin'));}
        $value = Cache::store('redis')->get($remote_device);
        if ($value !== $token) {$this->redirect(url('login/expireLogin'));}
        if ($this->common->verifyToken($token) == false) {$this->redirect(url('login/expireLogin'));}
    }

    /**
     * [getVerifyCode description]获取验证码
     * @return [type] [description]
     */
    public function getVerifyCode()
    {
        if (Request()->isPost()) {
            $data     = Request()->param();
            $validate = new UniversalValidate();
            if (!$validate->scene('getVerifyCode')->check($data)) {
                return json_return(301, $validate->getError());
            }
            $ip = Request()->ip();
            // 同一IP每分钟只能请求一次
            if (Cache::store('redis')->get('ztouch_ip_' . $ip)) {
                return json_return(302, '请求过于频繁');
            }
            // 同一手机号， 每天只能请求10条短信验证码
            if (Cache::store('redis')->get('ztouch_times_' . $data['phone']) >= 10) {
                return json_return(303, '你今天已经请求了很多次了，请明天再来。');
            }
            // 验证验证码是否过期
            if (Cache::store('redis')->get('captcha_' . $data['phone'])) {
                return json_return(304, '上一条验证码未过期，请直接输入');
            }
            $ztouch = new ZeroTouch();
            $res    = $ztouch->sendVertifyMsg($data['phone'], $ip);
            return $res ? json_return(200, '获取验证码成功') : json_return(305, '获取短信验证码失败');
        } else {
            return json_return(399, '非法请求');
        }

    }

    /**
     * 上传头像
     * @return [type] [description]
     */
    public function uploadHeadImage()
    {
        if (request()->isPost()) {
            $data             = request()->param();
            $data['head_img'] = request()->file('head_img');
            $validate         = new UniversalValidate();
            if (!$validate->scene('checkHeadImage')->check($data)) {
                return json_return(301, $validate->getError());
            }
            if (getimagesize($data['head_img']->getPathName()) == false) {return json_return(302, '不是有效得图片');}
            $width    = 150;
            $height   = 150;
            $base_url = '/uploads/user/head/';
            $url      = '.' . $base_url . $width . "_" . $height;
            if (!file_exists($url)) {
                mkdir($url, 0777, true);
            }
            $head_info = $this->handleImage($data['head_img'], $width, $height, $base_url . $width . "_" . $height);
            $res       = model('User')->get($data['user_id'])->save(['head_protrait' => $head_info, 'ctime' => date('Y-m-d H:i:s', time())]);
            return $res ? json_return(200, '上传头像成功', ['url' => $head_info]) : json_return(303, '上传头像信息失败');
        } else {
            return json_return(399, '非法请求');
        }

    }

    /**
     * 完善新用户注册信息
     */
    public function setUserInfo()
    {
        if (request()->isPost()) {
            $data     = request()->param();
            $validate = new UniversalValidate();
            if (!$validate->scene('checkUserInfo')->check($data)) {
                return json_return(301, $validate->getError());
            }
            $res = model('User')->get([$data['user_id']])->save(['name' => $data['user_nickname'], 'gender' => $data['user_gender'], 'age' => $data['user_age'], 'ctime' => date('Y-m-d H:i:s', time())]);
            return $res ? json_return(200, '保存用户信息成功') : json_return(302, '保存用户信息失败');
        } else {
            return json_return(399, '非法请求');
        }

    }

    /**
     * 单图上传
     */
    public function upload($file, $url)
    {
        // 移动到服务器的上传目录 并且使用uniqid规则
        if (!file_exists($url)) {
            mkdir($url, 0777, true);
        }
        $info = $file->rule('uniqid')->move($url);
        return $info ? $url . str_replace('\\', '/', $info->getSaveName()) : $info->getError();
    }

    /**
     * 多图上传
     */
    public function uploadsFiles($files, $width, $height, $url)
    {
        $urls = [];
        if (!file_exists('.' . $url)) {
            mkdir('.' . $url, 0777, true);
        }
        foreach ($files as $file) {
            $urls[] = $this->handleImage($file, $width, $height, $url);
        }
        return $urls;
    }

    /**
     * 处理图像(生成缩略图)
     */
    public function handleImage($file, $width, $height, $url)
    {
        $image     = \think\Image::open($file);
        $file_name = uniqid("z_touch") . '.' . $image->type();
        $image->thumb($width, $height, 6)->save('.' . $url . '/' . $file_name);
        return $url . $file_name;
        // return ['url' => $url . '/' . $file_name, 'filename' => $file_name];
    }

    // 生成唯一的文件名
    public function get_file_name($len)
    {
        return substr(sha1(date('YmdHis', time()) . uniqid('zero_touch')), 0, $len);
    }

    public function test()
    {
        // echo model('User')->where(['id' => 6])->hidden(['is_del', 'mtime'])->find();
        halt($_SERVER);
    }

    public function test1()
    {
        echo "8984" . $abc;
    }

}
